package com.ss.mq.pattern.pubsub;

import com.rabbitmq.client.*;
import com.ss.mq.util.RabbitUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author 叁昇
 * @create 2020-12-13-18:49
 */
public class PubSubConsumer {
    public static void main(String[] args) throws Exception {
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        // 定义交换机
        channel.exchangeDeclare("fanout_log", BuiltinExchangeType.FANOUT);

        // 自动生成队列名称
        String queue = channel.queueDeclare().getQueue();

        // 将自动生成的队列绑定到 log 交换机, fanout 交换机会忽略第三个参数, 即 routingKey, 填空串不能填 null!
        channel.queueBind(queue, "fanout_log", "");

        System.out.println("等待接收消息...");

        DeliverCallback deliver = (s, delivery) -> {
            String msg = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("收到: [ "+ msg +" ]");
        };

        CancelCallback cancel = s -> {};

        // 消费消息
        channel.basicConsume(queue, true, deliver, cancel);
    }
}
